package com.xinxin.base.util;

import org.apache.commons.codec.binary.Hex;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    private static final String ALGORITHM_NAME = "md5";
    private static final int HASH_ITERATIONS = 3;

    public static String encode(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }

    public static String encrypt(String username, String password) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance(ALGORITHM_NAME);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("password encrypt error.", e);
        }

        digest.reset();
        digest.update(username.getBytes(StandardCharsets.UTF_8));

        byte[] hashed = password.getBytes(StandardCharsets.UTF_8);
        int iterations = HASH_ITERATIONS;
        do {
            hashed = digest.digest(hashed);
            digest.reset();
        } while (--iterations > 0);

        return Hex.encodeHexString(hashed).toUpperCase();
    }

    public static void main(String[] args) {
        System.out.println(encode("123456"));
        System.out.println(encrypt("test19", "123456"));
    }
}
